<template>
  <div>
    <el-button
      icon="el-icon-circle-plus"
      circle
      @click="dialogFormVisible = true"
    ></el-button>
    <el-table :data="userList" stripe style="width: 100%">
      <el-table-column prop="username" label="用户名" width="140">
      </el-table-column>
      <el-table-column prop="role_name" label="角色" width="140">
      </el-table-column>
      <el-table-column prop="mobile" label="电话"> </el-table-column>
      <el-table-column prop="email" label="邮箱"> </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click="deleteUser(scope.row)"
          ></el-button>
          <el-button
            icon="el-icon-s-tools"
            circle
            @click="getUserRoot(scope.row)"
          ></el-button>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :change="changeSaveUserInfo(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="severalData"
    >
    </el-pagination>
    <!-- 对话框 -->

    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <el-form :model="addUserData">
        <el-form-item label="用户名">
          <el-input
            autocomplete="off"
            v-model="addUserData.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            autocomplete="off"
            v-model="addUserData.password"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input autocomplete="off" v-model="addUserData.email"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input autocomplete="off" v-model="addUserData.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="postUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑用户信息 -->
    <el-dialog title="编辑用户信息" :visible.sync="dialogFormUserInfo">
      <el-form :model="editUserInfo">
        <el-form-item label="用户名">
          <el-input
            disabled
            autocomplete="off"
            v-model="editUserInfo.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            disabled
            autocomplete="off"
            v-model="editUserInfo.password"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input autocomplete="off" v-model="editUserInfo.email"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input autocomplete="off" v-model="editUserInfo.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormUserInfo = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 角色管理 -->
    <el-dialog title="编辑用户信息" :visible.sync="dialogFormRoot">
      <el-form :model="editUserInfo">
        <el-form-item label="用户名">
          <el-input
            disabled
            autocomplete="off"
            v-model="editUserInfo.username"
          ></el-input>
        </el-form-item>
        <!-- 选择器 -->
        <el-select v-model="editUserInfo.role_name" placeholder="请选择">
          <el-option
            v-for="item in userRootData"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormRoot = false">取 消</el-button>
        <el-button type="primary" @click="toolsUserRoot">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 角色结束 -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      userList: [],
      severalData: 1,
      total: 0,
      pageSize: 2,
      pageNum: 1,
      dialogFormVisible: false,
      dialogFormUserInfo: false,
      dialogFormRoot: false,
      addUserData: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      editUserInfo: {},//修改用户角色修改共用
      userRootData:[],
      userRootName:''
    };
  },
  mounted() {
    this.getusers(this.pageNum, this.pageSize);
  },
  methods: {
    //设置用户角色
   async toolsUserRoot(){
      const { data:{data,meta} } = await this.$req.put(
        `/users/${this.editUserInfo.id}/role`,
        { rid: this.editUserInfo.role_name }
      );
      if(meta.status === 200){
        this.$message.success(meta.msg)
        this.getusers(this.pageNum,this.pageSize)
      }else if (meta.status !== 200) {
        this.$message.error(meta.msg)
      }
      this.dialogFormRoot = false
    },

    //用户角色管理
    getUserRoot(userinfo) {
      this.dialogFormRoot = true;
      this.editUserInfo = userinfo;
      this.$req.get("/roles").then((res) => {
        let {
          data: { data, meta },
        } = res;
        if (meta.status === 200) {
          this.userRootData = data
        }
      });
    },

    // 删除用户信息
    deleteUser(userinfo) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(userinfo.id);
          this.$req.delete("/users/" + userinfo.id).then((res) => {
            console.log(res);
            if (res.data.meta.status === 200) {
              console.log(11111);
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //修改用户状态
    async changeSaveUserInfo(userinfo) {
      // console.log(userinfo.mg_state);
      let {
        data: { data, meta },
      } = await this.$req.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (meta.status !== 200) {
        this.getusers(this.pageNum, this.pageSize);
      }
    },
    // 打开编辑用户
    handleEdit(userinfo) {
      this.editUserInfo = userinfo;
      this.dialogFormUserInfo = true;
      console.log(this.editUserInfo);
    },
    // 编辑用户
    async editUser() {
      let {
        data: { data, meta },
      } = await this.$req.put(`/users/${this.editUserInfo.id}`, {
        email: this.editUserInfo.email,
        mobile: this.editUserInfo.mobile,
      });
      this.dialogFormUserInfo = false;
      if (meta.status === 200) {
        this.$message({
          type: "success",
          message: meta.msg,
        });
      } else if (meta.status !== 200) {
        // ====================完成修改数据失败后的数据错误问题
        this.getusers(this.pageNum, this.pageSize);
        this.$message.error(meta.msg);
      }
    },
    async postUser() {
      //添加用户
      let {
        //  解构赋值
        data: { data, meta },
      } = await this.$req.post("users", this.addUserData);
      if (meta.status === 201) {
        //服务器返回201,说明添加成功
        this.dialogFormVisible = false;
        for (const key in this.addUserData) {
          this.addUserData[key] = null;
        }
        this.$message({
          type: "success",
          message: meta.msg,
        });
        this.getusers();
      }
    },

    async getusers(pagenum = 1, pagesize = 2) {
      let {
        data: { data, meta },
      } = await this.$req.get(`/users?pagenum=${pagenum}&pagesize=${pagesize}`);
      if (meta.status !== 200) {
        this.$message({
          showClose: true,
          message: "获取用户数据失败",
          type: "error",
        });
      } else if (meta.status === 200) {
        this.userList = data.users;
        this.severalData = data.total;
        console.log(this.userList);
      }
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.getusers(pageNum, this.pageSize);
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getusers(this.pageNum, pageSize);
    },
  },
};
</script>

<style>
::-webkit-scrollbar {
  overflow-x: scroll;
  white-space: nowrap;
  width: 0 !important;
}
::-webkit-scrollbar {
  overflow-x: scroll;
  white-space: nowrap;
  width: 0 !important;
  height: 0;
}
</style>